home *** CD-ROM | disk | FTP | other *** search
/ Aminet 38 / Aminet 38 (2000)(Schatztruhe)[!][Aug 2000].iso / Aminet / util / arc / bzip2_src.lha / bzip2-1.0.0 / bzip2.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-06-12  |  58.1 KB  |  2,051 lines

  1.  
  2. /*-----------------------------------------------------------*/
  3. /*--- A block-sorting, lossless compressor        bzip2.c ---*/
  4. /*-----------------------------------------------------------*/
  5.  
  6. /*--
  7.   This file is a part of bzip2 and/or libbzip2, a program and
  8.   library for lossless, block-sorting data compression.
  9.  
  10.   Copyright (C) 1996-2000 Julian R Seward.  All rights reserved.
  11.  
  12.   Redistribution and use in source and binary forms, with or without
  13.   modification, are permitted provided that the following conditions
  14.   are met:
  15.  
  16.   1. Redistributions of source code must retain the above copyright
  17.      notice, this list of conditions and the following disclaimer.
  18.  
  19.   2. The origin of this software must not be misrepresented; you must 
  20.      not claim that you wrote the original software.  If you use this 
  21.      software in a product, an acknowledgment in the product 
  22.      documentation would be appreciated but is not required.
  23.  
  24.   3. Altered source versions must be plainly marked as such, and must
  25.      not be misrepresented as being the original software.
  26.  
  27.   4. The name of the author may not be used to endorse or promote 
  28.      products derived from this software without specific prior written 
  29.      permission.
  30.  
  31.   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  32.   OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  33.   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34.   ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  35.   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  36.   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  37.   GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  38.   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  39.   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  40.   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  41.   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42.  
  43.   Julian Seward, Cambridge, UK.
  44.   jseward@acm.org
  45.   bzip2/libbzip2 version 1.0 of 21 March 2000
  46.  
  47.   This program is based on (at least) the work of:
  48.      Mike Burrows
  49.      David Wheeler
  50.      Peter Fenwick
  51.      Alistair Moffat
  52.      Radford Neal
  53.      Ian H. Witten
  54.      Robert Sedgewick
  55.      Jon L. Bentley
  56.  
  57.   For more information on these sources, see the manual.
  58. --*/
  59.  
  60.  
  61. /*----------------------------------------------------*/
  62. /*--- IMPORTANT                                    ---*/
  63. /*----------------------------------------------------*/
  64.  
  65. /*--
  66.    WARNING:
  67.       This program and library (attempts to) compress data by 
  68.       performing several non-trivial transformations on it.  
  69.       Unless you are 100% familiar with *all* the algorithms 
  70.       contained herein, and with the consequences of modifying them, 
  71.       you should NOT meddle with the compression or decompression 
  72.       machinery.  Incorrect changes can and very likely *will* 
  73.       lead to disasterous loss of data.
  74.  
  75.    DISCLAIMER:
  76.       I TAKE NO RESPONSIBILITY FOR ANY LOSS OF DATA ARISING FROM THE
  77.       USE OF THIS PROGRAM, HOWSOEVER CAUSED.
  78.  
  79.       Every compression of a file implies an assumption that the
  80.       compressed file can be decompressed to reproduce the original.
  81.       Great efforts in design, coding and testing have been made to
  82.       ensure that this program works correctly.  However, the
  83.       complexity of the algorithms, and, in particular, the presence
  84.       of various special cases in the code which occur with very low
  85.       but non-zero probability make it impossible to rule out the
  86.       possibility of bugs remaining in the program.  DO NOT COMPRESS
  87.       ANY DATA WITH THIS PROGRAM AND/OR LIBRARY UNLESS YOU ARE PREPARED 
  88.       TO ACCEPT THE POSSIBILITY, HOWEVER SMALL, THAT THE DATA WILL 
  89.       NOT BE RECOVERABLE.
  90.  
  91.       That is not to say this program is inherently unreliable.
  92.       Indeed, I very much hope the opposite is true.  bzip2/libbzip2
  93.       has been carefully constructed and extensively tested.
  94.  
  95.    PATENTS:
  96.       To the best of my knowledge, bzip2/libbzip2 does not use any 
  97.       patented algorithms.  However, I do not have the resources 
  98.       available to carry out a full patent search.  Therefore I cannot 
  99.       give any guarantee of the above statement.
  100. --*/
  101.  
  102.  
  103.  
  104. /*----------------------------------------------------*/
  105. /*--- and now for something much more pleasant :-) ---*/
  106. /*----------------------------------------------------*/
  107.  
  108. /*---------------------------------------------*/
  109. /*--
  110.   Place a 1 beside your platform, and 0 elsewhere.
  111. --*/
  112.  
  113. /*--
  114.   Generic 32-bit Unix.
  115.   Also works on 64-bit Unix boxes.
  116. --*/
  117. #define BZ_UNIX      1
  118.  
  119. /*--
  120.   Win32, as seen by Jacob Navia's excellent
  121.   port of (Chris Fraser & David Hanson)'s excellent
  122.   lcc compiler.
  123. --*/
  124. #define BZ_LCCWIN32  0
  125.  
  126. #if defined(_WIN32) && !defined(__CYGWIN__)
  127. #undef  BZ_LCCWIN32
  128. #define BZ_LCCWIN32 1
  129. #undef  BZ_UNIX
  130. #define BZ_UNIX 0
  131. #endif
  132.  
  133.  
  134. /*---------------------------------------------*/
  135. /*--
  136.   Some stuff for all platforms.
  137. --*/
  138.  
  139. #include <stdio.h>
  140. #include <stdlib.h>
  141. #include <string.h>
  142. #include <signal.h>
  143. #include <math.h>
  144. #include <errno.h>
  145. #include <ctype.h>
  146. #include "bzlib.h"
  147.  
  148. #define ERROR_IF_EOF(i)       { if ((i) == EOF)  ioError(); }
  149. #define ERROR_IF_NOT_ZERO(i)  { if ((i) != 0)    ioError(); }
  150. #define ERROR_IF_MINUS_ONE(i) { if ((i) == (-1)) ioError(); }
  151.  
  152.  
  153. /*---------------------------------------------*/
  154. /*--
  155.    Platform-specific stuff.
  156. --*/
  157.  
  158. #if BZ_UNIX
  159. #   include <sys/types.h>
  160. #   include <utime.h>
  161. #   include <unistd.h>
  162. #   include <sys/stat.h>
  163. #   include <sys/times.h>
  164.  
  165. #   define PATH_SEP    '/'
  166. #   define MY_LSTAT    lstat
  167. #   define MY_S_IFREG  S_ISREG
  168. #   define MY_STAT     stat
  169.  
  170. #   define APPEND_FILESPEC(root, name) \
  171.       root=snocString((root), (name))
  172.  
  173. #   define APPEND_FLAG(root, name) \
  174.       root=snocString((root), (name))
  175.  
  176. #   define SET_BINARY_MODE(fd) /**/
  177.  
  178. #   ifdef __GNUC__
  179. #      define NORETURN __attribute__ ((noreturn))
  180. #   else
  181. #      define NORETURN /**/
  182. #   endif
  183. #   ifdef __DJGPP__
  184. #     include <io.h>
  185. #     include <fcntl.h>
  186. #     undef MY_LSTAT
  187. #     define MY_LSTAT stat
  188. #     undef SET_BINARY_MODE
  189. #     define SET_BINARY_MODE(fd)                        \
  190.         do {                                            \
  191.            int retVal = setmode ( fileno ( fd ),        \
  192.                                  O_BINARY );            \
  193.            ERROR_IF_MINUS_ONE ( retVal );               \
  194.         } while ( 0 )
  195. #   endif
  196. #   ifdef __CYGWIN__
  197. #     include <io.h>
  198. #     include <fcntl.h>
  199. #     undef SET_BINARY_MODE
  200. #     define SET_BINARY_MODE(fd)                        \
  201.         do {                                            \
  202.            int retVal = setmode ( fileno ( fd ),        \
  203.                                  O_BINARY );            \
  204.            ERROR_IF_MINUS_ONE ( retVal );               \
  205.         } while ( 0 )
  206. #   endif
  207. #endif
  208.  
  209.  
  210.  
  211. #if BZ_LCCWIN32
  212. #   include <io.h>
  213. #   include <fcntl.h>
  214. #   include <sys\stat.h>
  215.  
  216. #   define NORETURN       /**/
  217. #   define PATH_SEP       '\\'
  218. #   define MY_LSTAT       _stat
  219. #   define MY_STAT        _stat
  220. #   define MY_S_IFREG(x)  ((x) & _S_IFREG)
  221.  
  222. #   define APPEND_FLAG(root, name) \
  223.       root=snocString((root), (name))
  224.  
  225. #   if 0
  226.    /*-- lcc-win32 seems to expand wildcards itself --*/
  227. #   define APPEND_FILESPEC(root, spec)                \
  228.       do {                                            \
  229.          if ((spec)[0] == '-') {                      \
  230.             root = snocString((root), (spec));        \
  231.          } else {                                     \
  232.             struct _finddata_t c_file;                \
  233.             long hFile;                               \
  234.             hFile = _findfirst((spec), &c_file);      \
  235.             if ( hFile == -1L ) {                     \
  236.                root = snocString ((root), (spec));    \
  237.             } else {                                  \
  238.                int anInt = 0;                         \
  239.                while ( anInt == 0 ) {                 \
  240.                   root = snocString((root),           \
  241.                             &c_file.name[0]);         \
  242.                   anInt = _findnext(hFile, &c_file);  \
  243.                }                                      \
  244.             }                                         \
  245.          }                                            \
  246.       } while ( 0 )
  247. #   else
  248. #   define APPEND_FILESPEC(root, name)                \
  249.       root = snocString ((root), (name))
  250. #   endif
  251.  
  252. #   define SET_BINARY_MODE(fd)                        \
  253.       do {                                            \
  254.          int retVal = setmode ( fileno ( fd ),        \
  255.                                O_BINARY );            \
  256.          ERROR_IF_MINUS_ONE ( retVal );               \
  257.       } while ( 0 )
  258.  
  259. #endif
  260.  
  261. #ifdef AMIGA
  262. #        undef MY_LSTAT
  263. #        define MY_LSTAT stat
  264. #endif
  265.  
  266. /*---------------------------------------------*/
  267. /*--
  268.   Some more stuff for all platforms :-)
  269. --*/
  270.  
  271. typedef char            Char;
  272. typedef unsigned char   Bool;
  273. typedef unsigned char   UChar;
  274. typedef int             Int32;
  275. typedef unsigned int    UInt32;
  276. typedef short           Int16;
  277. typedef unsigned short  UInt16;
  278.                                        
  279. #define True  ((Bool)1)
  280. #define False ((Bool)0)
  281.  
  282. /*--
  283.   IntNative is your platform's `native' int size.
  284.   Only here to avoid probs with 64-bit platforms.
  285. --*/
  286. typedef int IntNative;
  287.  
  288.  
  289. /*---------------------------------------------------*/
  290. /*--- Misc (file handling) data decls             ---*/
  291. /*---------------------------------------------------*/
  292.  
  293. Int32   verbosity;
  294. Bool    keepInputFiles, smallMode, deleteOutputOnInterrupt;
  295. Bool    forceOverwrite, testFailsExist, unzFailsExist, noisy;
  296. Int32   numFileNames, numFilesProcessed, blockSize100k;
  297. Int32   exitValue;
  298.  
  299. /*-- source modes; F==file, I==stdin, O==stdout --*/
  300. #define SM_I2O           1
  301. #define SM_F2O           2
  302. #define SM_F2F           3
  303.  
  304. /*-- operation modes --*/
  305. #define OM_Z             1
  306. #define OM_UNZ           2
  307. #define OM_TEST          3
  308.  
  309. Int32   opMode;
  310. Int32   srcMode;
  311.  
  312. #define FILE_NAME_LEN 1034
  313.  
  314. Int32   longestFileName;
  315. Char    inName [FILE_NAME_LEN];
  316. Char    outName[FILE_NAME_LEN];
  317. Char    tmpName[FILE_NAME_LEN];
  318. Char    *progName;
  319. Char    progNameReally[FILE_NAME_LEN];
  320. FILE    *outputHandleJustInCase;
  321. Int32   workFactor;
  322.  
  323. static void    panic                 ( Char* )   NORETURN;
  324. static void    ioError               ( void )    NORETURN;
  325. static void    outOfMemory           ( void )    NORETURN;
  326. static void    configError           ( void )    NORETURN;
  327. static void    crcError              ( void )    NORETURN;
  328. static void    cleanUpAndFail        ( Int32 )   NORETURN;
  329. static void    compressedStreamEOF   ( void )    NORETURN;
  330.  
  331. static void    copyFileName ( Char*, Char* );
  332. static void*   myMalloc     ( Int32 );
  333.  
  334.  
  335.  
  336. /*---------------------------------------------------*/
  337. /*--- An implementation of 64-bit ints.  Sigh.    ---*/
  338. /*--- Roll on widespread deployment of ANSI C9X ! ---*/
  339. /*---------------------------------------------------*/
  340.  
  341. typedef
  342.    struct { UChar b[8]; } 
  343.    UInt64;
  344.  
  345. static
  346. void uInt64_from_UInt32s ( UInt64* n, UInt32 lo32, UInt32 hi32 )
  347. {
  348.    n->b[7] = (UChar)((hi32 >> 24) & 0xFF);
  349.    n->b[6] = (UChar)((hi32 >> 16) & 0xFF);
  350.    n->b[5] = (UChar)((hi32 >> 8)  & 0xFF);
  351.    n->b[4] = (UChar) (hi32        & 0xFF);
  352.    n->b[3] = (UChar)((lo32 >> 24) & 0xFF);
  353.    n->b[2] = (UChar)((lo32 >> 16) & 0xFF);
  354.    n->b[1] = (UChar)((lo32 >> 8)  & 0xFF);
  355.    n->b[0] = (UChar) (lo32        & 0xFF);
  356. }
  357.  
  358. static
  359. double uInt64_to_double ( UInt64* n )
  360. {
  361.    Int32  i;
  362.    double base = 1.0;
  363.    double sum  = 0.0;
  364.    for (i = 0; i < 8; i++) {
  365.       sum  += base * (double)(n->b[i]);
  366.       base *= 256.0;
  367.    }
  368.    return sum;
  369. }
  370.  
  371. static
  372. void uInt64_add ( UInt64* src, UInt64* dst )
  373. {
  374.    Int32 i;
  375.    Int32 carry = 0;
  376.    for (i = 0; i < 8; i++) {
  377.       carry += ( ((Int32)src->b[i]) + ((Int32)dst->b[i]) );
  378.       dst->b[i] = (UChar)(carry & 0xFF);
  379.       carry >>= 8;
  380.    }
  381. }
  382.  
  383. static
  384. void uInt64_sub ( UInt64* src, UInt64* dst )
  385. {
  386.    Int32 t, i;
  387.    Int32 borrow = 0;
  388.    for (i = 0; i < 8; i++) {
  389.       t = ((Int32)dst->b[i]) - ((Int32)src->b[i]) - borrow;
  390.       if (t < 0) {
  391.          dst->b[i] = (UChar)(t + 256);
  392.          borrow = 1;
  393.       } else {
  394.          dst->b[i] = (UChar)t;
  395.          borrow = 0;
  396.       }
  397.    }
  398. }
  399.  
  400. static
  401. void uInt64_mul ( UInt64* a, UInt64* b, UInt64* r_hi, UInt64* r_lo )
  402. {
  403.    UChar sum[16];
  404.    Int32 ia, ib, carry;
  405.    for (ia = 0; ia < 16; ia++) sum[ia] = 0;
  406.    for (ia = 0; ia < 8; ia++) {
  407.       carry = 0;
  408.       for (ib = 0; ib < 8; ib++) {
  409.          carry += ( ((Int32)sum[ia+ib]) 
  410.                     + ((Int32)a->b[ia]) * ((Int32)b->b[ib]) );
  411.          sum[ia+ib] = (UChar)(carry & 0xFF);
  412.          carry >>= 8;
  413.       }
  414.       sum[ia+8] = (UChar)(carry & 0xFF);
  415.       if ((carry >>= 8) != 0) panic ( "uInt64_mul" );
  416.    }
  417.  
  418.    for (ia = 0; ia < 8; ia++) r_hi->b[ia] = sum[ia+8];
  419.    for (ia = 0; ia < 8; ia++) r_lo->b[ia] = sum[ia];
  420. }
  421.  
  422.  
  423. static
  424. void uInt64_shr1 ( UInt64* n )
  425. {
  426.    Int32 i;
  427.    for (i = 0; i < 8; i++) {
  428.       n->b[i] >>= 1;
  429.       if (i < 7 && (n->b[i+1] & 1)) n->b[i] |= 0x80;
  430.    }
  431. }
  432.  
  433. static
  434. void uInt64_shl1 ( UInt64* n )
  435. {
  436.    Int32 i;
  437.    for (i = 7; i >= 0; i--) {
  438.       n->b[i] <<= 1;
  439.       if (i > 0 && (n->b[i-1] & 0x80)) n->b[i]++;
  440.    }
  441. }
  442.  
  443. static
  444. Bool uInt64_isZero ( UInt64* n )
  445. {
  446.    Int32 i;
  447.    for (i = 0; i < 8; i++)
  448.       if (n->b[i] != 0) return 0;
  449.    return 1;
  450. }
  451.  
  452. static
  453. Int32 uInt64_qrm10 ( UInt64* n )
  454. {
  455.    /* Divide *n by 10, and return the remainder.  Long division
  456.       is difficult, so we cheat and instead multiply by
  457.       0xCCCC CCCC CCCC CCCD, which is 0.8 (viz, 0.1 << 3).
  458.    */
  459.    Int32  i;
  460.    UInt64 tmp1, tmp2, n_orig, zero_point_eight;
  461.  
  462.    zero_point_eight.b[1] = zero_point_eight.b[2] = 
  463.    zero_point_eight.b[3] = zero_point_eight.b[4] = 
  464.    zero_point_eight.b[5] = zero_point_eight.b[6] = 
  465.    zero_point_eight.b[7] = 0xCC;
  466.    zero_point_eight.b[0] = 0xCD;
  467.  
  468.    n_orig = *n;
  469.  
  470.    /* divide n by 10, 
  471.       by multiplying by 0.8 and then shifting right 3 times */
  472.    uInt64_mul ( n, &zero_point_eight, &tmp1, &tmp2 );
  473.    uInt64_shr1(&tmp1); uInt64_shr1(&tmp1); uInt64_shr1(&tmp1); 
  474.    *n = tmp1;
  475.    
  476.    /* tmp1 = 8*n, tmp2 = 2*n */
  477.    uInt64_shl1(&tmp1); uInt64_shl1(&tmp1); uInt64_shl1(&tmp1);
  478.    tmp2 = *n; uInt64_shl1(&tmp2);
  479.  
  480.    /* tmp1 = 10*n */
  481.    uInt64_add ( &tmp2, &tmp1 );
  482.  
  483.    /* n_orig = n_orig - 10*n */
  484.    uInt64_sub ( &tmp1, &n_orig );
  485.  
  486.    /* n_orig should now hold quotient, in range 0 .. 9 */
  487.    for (i = 7; i >= 1; i--) 
  488.       if (n_orig.b[i] != 0) panic ( "uInt64_qrm10(1)" );
  489.    if (n_orig.b[0] > 9)
  490.       panic ( "uInt64_qrm10(2)" );
  491.  
  492.    return (int)n_orig.b[0];
  493. }
  494.  
  495. /* ... and the Whole Entire Point of all this UInt64 stuff is
  496.    so that we can supply the following function.
  497. */
  498. static
  499. void uInt64_toAscii ( char* outbuf, UInt64* n )
  500. {
  501.    Int32  i, q;
  502.    UChar  buf[32];
  503.    Int32  nBuf   = 0;
  504.    UInt64 n_copy = *n;
  505.    do {
  506.       q = uInt64_qrm10 ( &n_copy );
  507.       buf[nBuf] = q + '0';
  508.       nBuf++;
  509.    } while (!uInt64_isZero(&n_copy));
  510.    outbuf[nBuf] = 0;
  511.    for (i = 0; i < nBuf; i++) outbuf[i] = buf[nBuf-i-1];
  512. }
  513.  
  514.  
  515. /*---------------------------------------------------*/
  516. /*--- Processing of complete files and streams    ---*/
  517. /*---------------------------------------------------*/
  518.  
  519. /*---------------------------------------------*/
  520. static 
  521. Bool myfeof ( FILE* f )
  522. {
  523.    Int32 c = fgetc ( f );
  524.    if (c == EOF) return True;
  525.    ungetc ( c, f );
  526.    return False;
  527. }
  528.  
  529.  
  530. /*---------------------------------------------*/
  531. static 
  532. void compressStream ( FILE *stream, FILE *zStream )
  533. {
  534.    BZFILE* bzf = NULL;
  535.    UChar   ibuf[5000];
  536.    Int32   nIbuf;
  537.    UInt32  nbytes_in_lo32, nbytes_in_hi32;
  538.    UInt32  nbytes_out_lo32, nbytes_out_hi32;
  539.    Int32   bzerr, bzerr_dummy, ret;
  540.  
  541.    SET_BINARY_MODE(stream);
  542.    SET_BINARY_MODE(zStream);
  543.  
  544.    if (ferror(stream)) goto errhandler_io;
  545.    if (ferror(zStream)) goto errhandler_io;
  546.  
  547.    bzf = BZ2_bzWriteOpen ( &bzerr, zStream, 
  548.                            blockSize100k, verbosity, workFactor );   
  549.    if (bzerr != BZ_OK) goto errhandler;
  550.  
  551.    if (verbosity >= 2) fprintf ( stderr, "\n" );
  552.  
  553.    while (True) {
  554.  
  555.       if (myfeof(stream)) break;
  556.       nIbuf = fread ( ibuf, sizeof(UChar), 5000, stream );
  557.       if (ferror(stream)) goto errhandler_io;
  558.       if (nIbuf > 0) BZ2_bzWrite ( &bzerr, bzf, (void*)ibuf, nIbuf );
  559.       if (bzerr != BZ_OK) goto errhandler;
  560.  
  561.    }
  562.  
  563.    BZ2_bzWriteClose64 ( &bzerr, bzf, 0, 
  564.                         &nbytes_in_lo32, &nbytes_in_hi32,
  565.                         &nbytes_out_lo32, &nbytes_out_hi32 );
  566.    if (bzerr != BZ_OK) goto errhandler;
  567.  
  568.    if (ferror(zStream)) goto errhandler_io;
  569.    ret = fflush ( zStream );
  570.    if (ret == EOF) goto errhandler_io;
  571.    if (zStream != stdout) {
  572.       ret = fclose ( zStream );
  573.       if (ret == EOF) goto errhandler_io;
  574.    }
  575.    if (ferror(stream)) goto errhandler_io;
  576.    ret = fclose ( stream );
  577.    if (ret == EOF) goto errhandler_io;
  578.  
  579.    if (nbytes_in_lo32 == 0 && nbytes_in_hi32 == 0) 
  580.       nbytes_in_lo32 = 1;
  581.  
  582.    if (verbosity >= 1) {
  583.       Char   buf_nin[32], buf_nout[32];
  584.       UInt64 nbytes_in,   nbytes_out;
  585.       double nbytes_in_d, nbytes_out_d;
  586.       uInt64_from_UInt32s ( &nbytes_in, 
  587.                             nbytes_in_lo32, nbytes_in_hi32 );
  588.       uInt64_from_UInt32s ( &nbytes_out, 
  589.                             nbytes_out_lo32, nbytes_out_hi32 );
  590.       nbytes_in_d  = uInt64_to_double ( &nbytes_in );
  591.       nbytes_out_d = uInt64_to_double ( &nbytes_out );
  592.       uInt64_toAscii ( buf_nin, &nbytes_in );
  593.       uInt64_toAscii ( buf_nout, &nbytes_out );
  594.       fprintf ( stderr, "%6.3f:1, %6.3f bits/byte, "
  595.                         "%5.2f%% saved, %s in, %s out.\n",
  596.                 nbytes_in_d / nbytes_out_d,
  597.                 (8.0 * nbytes_out_d) / nbytes_in_d,
  598.                 100.0 * (1.0 - nbytes_out_d / nbytes_in_d),
  599.                 buf_nin,
  600.                 buf_nout
  601.               );
  602.    }
  603.  
  604.    return;
  605.  
  606.    errhandler:
  607.    BZ2_bzWriteClose64 ( &bzerr_dummy, bzf, 1, 
  608.                         &nbytes_in_lo32, &nbytes_in_hi32,
  609.                         &nbytes_out_lo32, &nbytes_out_hi32 );
  610.    switch (bzerr) {
  611.       case BZ_CONFIG_ERROR:
  612.          configError(); break;
  613.       case BZ_MEM_ERROR:
  614.          outOfMemory (); break;
  615.       case BZ_IO_ERROR:
  616.          errhandler_io:
  617.          ioError(); break;
  618.       default:
  619.          panic ( "compress:unexpected error" );
  620.    }
  621.  
  622.    panic ( "compress:end" );
  623.    /*notreached*/
  624. }
  625.  
  626.  
  627.  
  628. /*---------------------------------------------*/
  629. static 
  630. Bool uncompressStream ( FILE *zStream, FILE *stream )
  631. {
  632.    BZFILE* bzf = NULL;
  633.    Int32   bzerr, bzerr_dummy, ret, nread, streamNo, i;
  634.    UChar   obuf[5000];
  635.    UChar   unused[BZ_MAX_UNUSED];
  636.    Int32   nUnused;
  637.    UChar*  unusedTmp;
  638.  
  639.    nUnused = 0;
  640.    streamNo = 0;
  641.  
  642.    SET_BINARY_MODE(stream);
  643.    SET_BINARY_MODE(zStream);
  644.  
  645.    if (ferror(stream)) goto errhandler_io;
  646.    if (ferror(zStream)) goto errhandler_io;
  647.  
  648.    while (True) {
  649.  
  650.       bzf = BZ2_bzReadOpen ( 
  651.                &bzerr, zStream, verbosity, 
  652.                (int)smallMode, unused, nUnused
  653.             );
  654.       if (bzf == NULL || bzerr != BZ_OK) goto errhandler;
  655.       streamNo++;
  656.  
  657.       while (bzerr == BZ_OK) {
  658.          nread = BZ2_bzRead ( &bzerr, bzf, obuf, 5000 );
  659.          if (bzerr == BZ_DATA_ERROR_MAGIC) goto errhandler;
  660.          if ((bzerr == BZ_OK || bzerr == BZ_STREAM_END) && nread > 0)
  661.             fwrite ( obuf, sizeof(UChar), nread, stream );
  662.          if (ferror(stream)) goto errhandler_io;
  663.       }
  664.       if (bzerr != BZ_STREAM_END) goto errhandler;
  665.  
  666.       BZ2_bzReadGetUnused ( &bzerr, bzf, (void**)(&unusedTmp), &nUnused );
  667.       if (bzerr != BZ_OK) panic ( "decompress:bzReadGetUnused" );
  668.  
  669.       for (i = 0; i < nUnused; i++) unused[i] = unusedTmp[i];
  670.  
  671.       BZ2_bzReadClose ( &bzerr, bzf );
  672.       if (bzerr != BZ_OK) panic ( "decompress:bzReadGetUnused" );
  673.  
  674.       if (nUnused == 0 && myfeof(zStream)) break;
  675.  
  676.    }
  677.  
  678.    if (ferror(zStream)) goto errhandler_io;
  679.    ret = fclose ( zStream );
  680.    if (ret == EOF) goto errhandler_io;
  681.  
  682.    if (ferror(stream)) goto errhandler_io;
  683.    ret = fflush ( stream );
  684.    if (ret != 0) goto errhandler_io;
  685.    if (stream != stdout) {
  686.       ret = fclose ( stream );
  687.       if (ret == EOF) goto errhandler_io;
  688.    }
  689.    if (verbosity >= 2) fprintf ( stderr, "\n    " );
  690.    return True;
  691.  
  692.    errhandler:
  693.    BZ2_bzReadClose ( &bzerr_dummy, bzf );
  694.    switch (bzerr) {
  695.       case BZ_CONFIG_ERROR:
  696.          configError(); break;
  697.       case BZ_IO_ERROR:
  698.          errhandler_io:
  699.          ioError(); break;
  700.       case BZ_DATA_ERROR:
  701.          crcError();
  702.       case BZ_MEM_ERROR:
  703.          outOfMemory();
  704.       case BZ_UNEXPECTED_EOF:
  705.          compressedStreamEOF();
  706.       case BZ_DATA_ERROR_MAGIC:
  707.          if (zStream != stdin) fclose(zStream);
  708.          if (stream != stdout) fclose(stream);
  709.          if (streamNo == 1) {
  710.             return False;
  711.          } else {
  712.             if (noisy)
  713.             fprintf ( stderr, 
  714.                       "\n%s: %s: trailing garbage after EOF ignored\n",
  715.                       progName, inName );
  716.             return True;       
  717.          }
  718.       default:
  719.          panic ( "decompress:unexpected error" );
  720.    }
  721.  
  722.    panic ( "decompress:end" );
  723.    return True; /*notreached*/
  724. }
  725.  
  726.  
  727. /*---------------------------------------------*/
  728. static 
  729. Bool testStream ( FILE *zStream )
  730. {
  731.    BZFILE* bzf = NULL;
  732.    Int32   bzerr, bzerr_dummy, ret, nread, streamNo, i;
  733.    UChar   obuf[5000];
  734.    UChar   unused[BZ_MAX_UNUSED];
  735.    Int32   nUnused;
  736.    UChar*  unusedTmp;
  737.  
  738.    nUnused = 0;
  739.    streamNo = 0;
  740.  
  741.    SET_BINARY_MODE(zStream);
  742.    if (ferror(zStream)) goto errhandler_io;
  743.  
  744.    while (True) {
  745.  
  746.       bzf = BZ2_bzReadOpen ( 
  747.                &bzerr, zStream, verbosity, 
  748.                (int)smallMode, unused, nUnused
  749.             );
  750.       if (bzf == NULL || bzerr != BZ_OK) goto errhandler;
  751.       streamNo++;
  752.  
  753.       while (bzerr == BZ_OK) {
  754.          nread = BZ2_bzRead ( &bzerr, bzf, obuf, 5000 );
  755.          if (bzerr == BZ_DATA_ERROR_MAGIC) goto errhandler;
  756.       }
  757.       if (bzerr != BZ_STREAM_END) goto errhandler;
  758.  
  759.       BZ2_bzReadGetUnused ( &bzerr, bzf, (void**)(&unusedTmp), &nUnused );
  760.       if (bzerr != BZ_OK) panic ( "test:bzReadGetUnused" );
  761.  
  762.       for (i = 0; i < nUnused; i++) unused[i] = unusedTmp[i];
  763.  
  764.       BZ2_bzReadClose ( &bzerr, bzf );
  765.       if (bzerr != BZ_OK) panic ( "test:bzReadGetUnused" );
  766.       if (nUnused == 0 && myfeof(zStream)) break;
  767.  
  768.    }
  769.  
  770.    if (ferror(zStream)) goto errhandler_io;
  771.    ret = fclose ( zStream );
  772.    if (ret == EOF) goto errhandler_io;
  773.  
  774.    if (verbosity >= 2) fprintf ( stderr, "\n    " );
  775.    return True;
  776.  
  777.    errhandler:
  778.    BZ2_bzReadClose ( &bzerr_dummy, bzf );
  779.    if (verbosity == 0) 
  780.       fprintf ( stderr, "%s: %s: ", progName, inName );
  781.    switch (bzerr) {
  782.       case BZ_CONFIG_ERROR:
  783.          configError(); break;
  784.       case BZ_IO_ERROR:
  785.          errhandler_io:
  786.          ioError(); break;
  787.       case BZ_DATA_ERROR:
  788.          fprintf ( stderr,
  789.                    "data integrity (CRC) error in data\n" );
  790.          return False;
  791.       case BZ_MEM_ERROR:
  792.          outOfMemory();
  793.       case BZ_UNEXPECTED_EOF:
  794.          fprintf ( stderr,
  795.                    "file ends unexpectedly\n" );
  796.          return False;
  797.       case BZ_DATA_ERROR_MAGIC:
  798.          if (zStream != stdin) fclose(zStream);
  799.          if (streamNo == 1) {
  800.           fprintf ( stderr, 
  801.                     "bad magic number (file not created by bzip2)\n" );
  802.             return False;
  803.          } else {
  804.             if (noisy)
  805.             fprintf ( stderr, 
  806.                       "trailing garbage after EOF ignored\n" );
  807.             return True;       
  808.          }
  809.       default:
  810.          panic ( "test:unexpected error" );
  811.    }
  812.  
  813.    panic ( "test:end" );
  814.    return True; /*notreached*/
  815. }
  816.  
  817.  
  818. /*---------------------------------------------------*/
  819. /*--- Error [non-] handling grunge                ---*/
  820. /*---------------------------------------------------*/
  821.  
  822. /*---------------------------------------------*/
  823. static
  824. void setExit ( Int32 v )
  825. {
  826.    if (v > exitValue) exitValue = v;
  827. }
  828.  
  829.  
  830. /*---------------------------------------------*/
  831. static 
  832. void cadvise ( void )
  833. {
  834.    if (noisy)
  835.    fprintf (
  836.       stderr,
  837.       "\nIt is possible that the compressed file(s) have become corrupted.\n"
  838.         "You can use the -tvv option to test integrity of such files.\n\n"
  839.         "You can use the `bzip2recover' program to *attempt* to recover\n"
  840.         "data from undamaged sections of corrupted files.\n\n"
  841.     );
  842. }
  843.  
  844.  
  845. /*---------------------------------------------*/
  846. static 
  847. void showFileNames ( void )
  848. {
  849.    if (noisy)
  850.    fprintf (
  851.       stderr,
  852.       "\tInput file = %s, output file = %s\n",
  853.       inName, outName 
  854.    );
  855. }
  856.  
  857.  
  858. /*---------------------------------------------*/
  859. static 
  860. void cleanUpAndFail ( Int32 ec )
  861. {
  862.    IntNative retVal;
  863.  
  864.    if ( srcMode == SM_F2F 
  865.         && opMode != OM_TEST
  866.         && deleteOutputOnInterrupt ) {
  867.       if (noisy)
  868.       fprintf ( stderr, "%s: Deleting output file %s, if it exists.\n",
  869.                 progName, outName );
  870.       if (outputHandleJustInCase != NULL)
  871.          fclose ( outputHandleJustInCase );
  872.       retVal = remove ( outName );
  873.       if (retVal != 0)
  874.          fprintf ( stderr,
  875.                    "%s: WARNING: deletion of output file (apparently) failed.\n",
  876.                    progName );
  877.    }
  878.    if (noisy && numFileNames > 0 && numFilesProcessed < numFileNames) {
  879.       fprintf ( stderr, 
  880.                 "%s: WARNING: some files have not been processed:\n"
  881.                 "\t%d specified on command line, %d not processed yet.\n\n",
  882.                 progName, numFileNames, 
  883.                           numFileNames - numFilesProcessed );
  884.    }
  885.    setExit(ec);
  886.    exit(exitValue);
  887. }
  888.  
  889.  
  890. /*---------------------------------------------*/
  891. static 
  892. void panic ( Char* s )
  893. {
  894.    fprintf ( stderr,
  895.              "\n%s: PANIC -- internal consistency error:\n"
  896.              "\t%s\n"
  897.              "\tThis is a BUG.  Please report it to me at:\n"
  898.              "\tjseward@acm.org\n",
  899.              progName, s );
  900.    showFileNames();
  901.    cleanUpAndFail( 3 );
  902. }
  903.  
  904.  
  905. /*---------------------------------------------*/
  906. static 
  907. void crcError ( void )
  908. {
  909.    fprintf ( stderr,
  910.              "\n%s: Data integrity error when decompressing.\n",
  911.              progName );
  912.    showFileNames();
  913.    cadvise();
  914.    cleanUpAndFail( 2 );
  915. }
  916.  
  917.  
  918. /*---------------------------------------------*/
  919. static 
  920. void compressedStreamEOF ( void )
  921. {
  922.    fprintf ( stderr,
  923.              "\n%s: Compressed file ends unexpectedly;\n\t"
  924.              "perhaps it is corrupted?  *Possible* reason follows.\n",
  925.              progName );
  926.    perror ( progName );
  927.    showFileNames();
  928.    cadvise();
  929.    cleanUpAndFail( 2 );
  930. }
  931.  
  932.  
  933. /*---------------------------------------------*/
  934. static 
  935. void ioError ( void )
  936. {
  937.    fprintf ( stderr,
  938.              "\n%s: I/O or other error, bailing out.  "
  939.              "Possible reason follows.\n",
  940.              progName );
  941.    perror ( progName );
  942.    showFileNames();
  943.    cleanUpAndFail( 1 );
  944. }
  945.  
  946.  
  947. /*---------------------------------------------*/
  948. static 
  949. void mySignalCatcher ( IntNative n )
  950. {
  951.    fprintf ( stderr,
  952.              "\n%s: Control-C or similar caught, quitting.\n",
  953.              progName );
  954.    cleanUpAndFail(1);
  955. }
  956.  
  957.  
  958. /*---------------------------------------------*/
  959. static 
  960. void mySIGSEGVorSIGBUScatcher ( IntNative n )
  961. {
  962.    if (opMode == OM_Z)
  963.       fprintf ( 
  964.       stderr,
  965.       "\n%s: Caught a SIGSEGV or SIGBUS whilst compressing.\n"
  966.       "\n"
  967.       "   Possible causes are (most likely first):\n"
  968.       "   (1) This computer has unreliable memory or cache hardware\n"
  969.       "       (a surprisingly common problem; try a different machine.)\n"
  970.       "   (2) A bug in the compiler used to create this executable\n"
  971.       "       (unlikely, if you didn't compile bzip2 yourself.)\n"
  972.       "   (3) A real bug in bzip2 -- I hope this should never be the case.\n"
  973.       "   The user's manual, Section 4.3, has more info on (1) and (2).\n"
  974.       "   \n"
  975.       "   If you suspect this is a bug in bzip2, or are unsure about (1)\n"
  976.       "   or (2), feel free to report it to me at: jseward@acm.org.\n"
  977.       "   Section 4.3 of the user's manual describes the info a useful\n"
  978.       "   bug report should have.  If the manual is available on your\n"
  979.       "   system, please try and read it before mailing me.  If you don't\n"
  980.       "   have the manual or can't be bothered to read it, mail me anyway.\n"
  981.       "\n",
  982.       progName );
  983.       else
  984.       fprintf ( 
  985.       stderr,
  986.       "\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing.\n"
  987.       "\n"
  988.       "   Possible causes are (most likely first):\n"
  989.       "   (1) The compressed data is corrupted, and bzip2's usual checks\n"
  990.       "       failed to detect this.  Try bzip2 -tvv my_file.bz2.\n"
  991.       "   (2) This computer has unreliable memory or cache hardware\n"
  992.       "       (a surprisingly common problem; try a different machine.)\n"
  993.       "   (3) A bug in the compiler used to create this executable\n"
  994.       "       (unlikely, if you didn't compile bzip2 yourself.)\n"
  995.       "   (4) A real bug in bzip2 -- I hope this should never be the case.\n"
  996.       "   The user's manual, Section 4.3, has more info on (2) and (3).\n"
  997.       "   \n"
  998.       "   If you suspect this is a bug in bzip2, or are unsure about (2)\n"
  999.       "   or (3), feel free to report it to me at: jseward@acm.org.\n"
  1000.       "   Section 4.3 of the user's manual describes the info a useful\n"
  1001.       "   bug report should have.  If the manual is available on your\n"
  1002.       "   system, please try and read it before mailing me.  If you don't\n"
  1003.       "   have the manual or can't be bothered to read it, mail me anyway.\n"
  1004.       "\n",
  1005.       progName );
  1006.  
  1007.    showFileNames();
  1008.    if (opMode == OM_Z)
  1009.       cleanUpAndFail( 3 ); else
  1010.       { cadvise(); cleanUpAndFail( 2 ); }
  1011. }
  1012.  
  1013.  
  1014. /*---------------------------------------------*/
  1015. static 
  1016. void outOfMemory ( void )
  1017. {
  1018.    fprintf ( stderr,
  1019.              "\n%s: couldn't allocate enough memory\n",
  1020.              progName );
  1021.    showFileNames();
  1022.    cleanUpAndFail(1);
  1023. }
  1024.  
  1025.  
  1026. /*---------------------------------------------*/
  1027. static 
  1028. void configError ( void )
  1029. {
  1030.    fprintf ( stderr,
  1031.              "bzip2: I'm not configured correctly for this platform!\n"
  1032.              "\tI require Int32, Int16 and Char to have sizes\n"
  1033.              "\tof 4, 2 and 1 bytes to run properly, and they don't.\n"
  1034.              "\tProbably you can fix this by defining them correctly,\n"
  1035.              "\tand recompiling.  Bye!\n" );
  1036.    setExit(3);
  1037.    exit(exitValue);
  1038. }
  1039.  
  1040.  
  1041. /*---------------------------------------------------*/
  1042. /*--- The main driver machinery                   ---*/
  1043. /*---------------------------------------------------*/
  1044.  
  1045. /*---------------------------------------------*/
  1046. static 
  1047. void pad ( Char *s )
  1048. {
  1049.    Int32 i;
  1050.    if ( (Int32)strlen(s) >= longestFileName ) return;
  1051.    for (i = 1; i <= longestFileName - (Int32)strlen(s); i++)
  1052.       fprintf ( stderr, " " );
  1053. }
  1054.  
  1055.  
  1056. /*---------------------------------------------*/
  1057. static 
  1058. void copyFileName ( Char* to, Char* from ) 
  1059. {
  1060.    if ( strlen(from) > FILE_NAME_LEN-10 )  {
  1061.       fprintf (
  1062.          stderr,
  1063.          "bzip2: file name\n`%s'\n"
  1064.          "is suspiciously (more than %d chars) long.\n"
  1065.          "Try using a reasonable file name instead.  Sorry! :-)\n",
  1066.          from, FILE_NAME_LEN-10
  1067.       );
  1068.       setExit(1);
  1069.       exit(exitValue);
  1070.    }
  1071.  
  1072.   strncpy(to,from,FILE_NAME_LEN-10);
  1073.   to[FILE_NAME_LEN-10]='\0';
  1074. }
  1075.  
  1076.  
  1077. /*---------------------------------------------*/
  1078. static 
  1079. Bool fileExists ( Char* name )
  1080. {
  1081.    FILE *tmp   = fopen ( name, "rb" );
  1082.    Bool exists = (tmp != NULL);
  1083.    if (tmp != NULL) fclose ( tmp );
  1084.    return exists;
  1085. }
  1086.  
  1087.  
  1088. /*---------------------------------------------*/
  1089. /*--
  1090.   if in doubt, return True
  1091. --*/
  1092. static 
  1093. Bool notAStandardFile ( Char* name )
  1094. {
  1095.    IntNative      i;
  1096.    struct MY_STAT statBuf;
  1097.  
  1098.    i = MY_LSTAT ( name, &statBuf );
  1099.    if (i != 0) return True;
  1100.    if (MY_S_IFREG(statBuf.st_mode)) return False;
  1101.    return True;
  1102. }
  1103.  
  1104.  
  1105. /*---------------------------------------------*/
  1106. /*--
  1107.   rac 11/21/98 see if file has hard links to it
  1108. --*/
  1109. static 
  1110. Int32 countHardLinks ( Char* name )
  1111. {  
  1112.    IntNative      i;
  1113.    struct MY_STAT statBuf;
  1114.  
  1115.    i = MY_LSTAT ( name, &statBuf );
  1116.    if (i != 0) return 0;
  1117.    return (statBuf.st_nlink - 1);
  1118. }
  1119.  
  1120.  
  1121. /*---------------------------------------------*/
  1122. static 
  1123. void copyDatePermissionsAndOwner ( Char *srcName, Char *dstName )
  1124. {
  1125. #ifndef AMIGA
  1126. #if BZ_UNIX
  1127.    IntNative      retVal;
  1128.    struct MY_STAT statBuf;
  1129.    struct utimbuf uTimBuf;
  1130.  
  1131.    retVal = MY_LSTAT ( srcName, &statBuf );
  1132.    ERROR_IF_NOT_ZERO ( retVal );
  1133.    uTimBuf.actime = statBuf.st_atime;
  1134.    uTimBuf.modtime = statBuf.st_mtime;
  1135.  
  1136.    retVal = chmod ( dstName, statBuf.st_mode );
  1137.    ERROR_IF_NOT_ZERO ( retVal );
  1138.  
  1139.    retVal = utime ( dstName, &uTimBuf );
  1140.    ERROR_IF_NOT_ZERO ( retVal );
  1141.  
  1142.    retVal = chown ( dstName, statBuf.st_uid, statBuf.st_gid );
  1143.    /* chown() will in many cases return with EPERM, which can
  1144.       be safely ignored.
  1145.    */
  1146. #endif
  1147. #endif
  1148. }
  1149.  
  1150.  
  1151. /*---------------------------------------------*/
  1152. static 
  1153. void setInterimPermissions ( Char *dstName )
  1154. {
  1155. #if BZ_UNIX
  1156.    IntNative      retVal;
  1157.    retVal = chmod ( dstName, S_IRUSR | S_IWUSR );
  1158.    ERROR_IF_NOT_ZERO ( retVal );
  1159. #endif
  1160. }
  1161.  
  1162.  
  1163. /*---------------------------------------------*/
  1164. static 
  1165. Bool containsDubiousChars ( Char* name )
  1166. {
  1167.    Bool cdc = False;
  1168.    for (; *name != '\0'; name++)
  1169.       if (*name == '?' || *name == '*') cdc = True;
  1170.    return cdc;
  1171. }
  1172.  
  1173.  
  1174. /*---------------------------------------------*/
  1175. #define BZ_N_SUFFIX_PAIRS 4
  1176.  
  1177. Char* zSuffix[BZ_N_SUFFIX_PAIRS] 
  1178.    = { ".bz2", ".bz", ".tbz2", ".tbz" };
  1179. Char* unzSuffix[BZ_N_SUFFIX_PAIRS] 
  1180.    = { "", "", ".tar", ".tar" };
  1181.  
  1182. static 
  1183. Bool hasSuffix ( Char* s, Char* suffix )
  1184. {
  1185.    Int32 ns = strlen(s);
  1186.    Int32 nx = strlen(suffix);
  1187.    if (ns < nx) return False;
  1188.    if (strcmp(s + ns - nx, suffix) == 0) return True;
  1189.    return False;
  1190. }
  1191.  
  1192. static 
  1193. Bool mapSuffix ( Char* name, 
  1194.                  Char* oldSuffix, Char* newSuffix )
  1195. {
  1196.    if (!hasSuffix(name,oldSuffix)) return False;
  1197.    name[strlen(name)-strlen(oldSuffix)] = 0;
  1198.    strcat ( name, newSuffix );
  1199.    return True;
  1200. }
  1201.  
  1202.  
  1203. /*---------------------------------------------*/
  1204. static 
  1205. void compress ( Char *name )
  1206. {
  1207.    FILE  *inStr;
  1208.    FILE  *outStr;
  1209.    Int32 n, i;
  1210.  
  1211.    deleteOutputOnInterrupt = False;
  1212.  
  1213.    if (name == NULL && srcMode != SM_I2O)
  1214.       panic ( "compress: bad modes\n" );
  1215.  
  1216.    switch (srcMode) {
  1217.       case SM_I2O: 
  1218.          copyFileName ( inName, "(stdin)" );
  1219.          copyFileName ( outName, "(stdout)" ); 
  1220.          break;
  1221.       case SM_F2F: 
  1222.          copyFileName ( inName, name );
  1223.          copyFileName ( outName, name );
  1224.          strcat ( outName, ".bz2" ); 
  1225.          break;
  1226.       case SM_F2O: 
  1227.          copyFileName ( inName, name );
  1228.          copyFileName ( outName, "(stdout)" ); 
  1229.          break;
  1230.    }
  1231.  
  1232.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  1233.       if (noisy)
  1234.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  1235.                 progName, inName );
  1236.       setExit(1);
  1237.       return;
  1238.    }
  1239.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  1240.       fprintf ( stderr, "%s: Can't open input file %s: %s.\n",
  1241.                 progName, inName, strerror(errno) );
  1242.       setExit(1);
  1243.       return;
  1244.    }
  1245.    for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) {
  1246.       if (hasSuffix(inName, zSuffix[i])) {
  1247.          if (noisy)
  1248.          fprintf ( stderr, 
  1249.                    "%s: Input file %s already has %s suffix.\n",
  1250.                    progName, inName, zSuffix[i] );
  1251.          setExit(1);
  1252.          return;
  1253.       }
  1254.    }
  1255.    if ( srcMode == SM_F2F && !forceOverwrite && notAStandardFile ( inName )) {
  1256.       if (noisy)
  1257.       fprintf ( stderr, "%s: Input file %s is not a normal file.\n",
  1258.                 progName, inName );
  1259.       setExit(1);
  1260.       return;
  1261.    }
  1262.    if ( srcMode == SM_F2F && !forceOverwrite && fileExists ( outName ) ) {
  1263.       fprintf ( stderr, "%s: Output file %s already exists.\n",
  1264.                 progName, outName );
  1265.       setExit(1);
  1266.       return;
  1267.    }
  1268.    if ( srcMode == SM_F2F && !forceOverwrite &&
  1269.         (n=countHardLinks ( inName )) > 0) {
  1270.       fprintf ( stderr, "%s: Input file %s has %d other link%s.\n",
  1271.                 progName, inName, n, n > 1 ? "s" : "" );
  1272.       setExit(1);
  1273.       return;
  1274.    }
  1275.  
  1276.    switch ( srcMode ) {
  1277.  
  1278.       case SM_I2O:
  1279.          inStr = stdin;
  1280.          outStr = stdout;
  1281.          if ( isatty ( fileno ( stdout ) ) ) {
  1282.             fprintf ( stderr,
  1283.                       "%s: I won't write compressed data to a terminal.\n",
  1284.                       progName );
  1285.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  1286.                               progName, progName );
  1287.             setExit(1);
  1288.             return;
  1289.          };
  1290.          break;
  1291.  
  1292.       case SM_F2O:
  1293.          inStr = fopen ( inName, "rb" );
  1294.          outStr = stdout;
  1295.          if ( isatty ( fileno ( stdout ) ) ) {
  1296.             fprintf ( stderr,
  1297.                       "%s: I won't write compressed data to a terminal.\n",
  1298.                       progName );
  1299.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  1300.                               progName, progName );
  1301.             if ( inStr != NULL ) fclose ( inStr );
  1302.             setExit(1);
  1303.             return;
  1304.          };
  1305.          if ( inStr == NULL ) {
  1306.             fprintf ( stderr, "%s: Can't open input file %s: %s.\n",
  1307.                       progName, inName, strerror(errno) );
  1308.             setExit(1);
  1309.             return;
  1310.          };
  1311.          break;
  1312.  
  1313.       case SM_F2F:
  1314.          inStr = fopen ( inName, "rb" );
  1315.          outStr = fopen ( outName, "wb" );
  1316.          if ( outStr == NULL) {
  1317.             fprintf ( stderr, "%s: Can't create output file %s: %s.\n",
  1318.                       progName, outName, strerror(errno) );
  1319.             if ( inStr != NULL ) fclose ( inStr );
  1320.             setExit(1);
  1321.             return;
  1322.          }
  1323.          if ( inStr == NULL ) {
  1324.             fprintf ( stderr, "%s: Can't open input file %s: %s.\n",
  1325.                       progName, inName, strerror(errno) );
  1326.             if ( outStr != NULL ) fclose ( outStr );
  1327.             setExit(1);
  1328.             return;
  1329.          };
  1330.          setInterimPermissions ( outName );
  1331.          break;
  1332.  
  1333.       default:
  1334.          panic ( "compress: bad srcMode" );
  1335.          break;
  1336.    }
  1337.  
  1338.    if (verbosity >= 1) {
  1339.       fprintf ( stderr,  "  %s: ", inName );
  1340.       pad ( inName );
  1341.       fflush ( stderr );
  1342.    }
  1343.  
  1344.    /*--- Now the input and output handles are sane.  Do the Biz. ---*/
  1345.    outputHandleJustInCase = outStr;
  1346.    deleteOutputOnInterrupt = True;
  1347.    compressStream ( inStr, outStr );
  1348.    outputHandleJustInCase = NULL;
  1349.  
  1350.    /*--- If there was an I/O error, we won't get here. ---*/
  1351.    if ( srcMode == SM_F2F ) {
  1352.       copyDatePermissionsAndOwner ( inName, outName );
  1353.       deleteOutputOnInterrupt = False;
  1354.       if ( !keepInputFiles ) {
  1355.          IntNative retVal = remove ( inName );
  1356.          ERROR_IF_NOT_ZERO ( retVal );
  1357.       }
  1358.    }
  1359.  
  1360.    deleteOutputOnInterrupt = False;
  1361. }
  1362.  
  1363.  
  1364. /*---------------------------------------------*/
  1365. static 
  1366. void uncompress ( Char *name )
  1367. {
  1368.    FILE  *inStr;
  1369.    FILE  *outStr;
  1370.    Int32 n, i;
  1371.    Bool  magicNumberOK;
  1372.    Bool  cantGuess;
  1373.  
  1374.    deleteOutputOnInterrupt = False;
  1375.  
  1376.    if (name == NULL && srcMode != SM_I2O)
  1377.       panic ( "uncompress: bad modes\n" );
  1378.  
  1379.    cantGuess = False;
  1380.    switch (srcMode) {
  1381.       case SM_I2O: 
  1382.          copyFileName ( inName, "(stdin)" );
  1383.          copyFileName ( outName, "(stdout)" ); 
  1384.          break;
  1385.       case SM_F2F: 
  1386.          copyFileName ( inName, name );
  1387.          copyFileName ( outName, name );
  1388.          for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++)
  1389.             if (mapSuffix(outName,zSuffix[i],unzSuffix[i]))
  1390.                goto zzz; 
  1391.          cantGuess = True;
  1392.          strcat ( outName, ".out" );
  1393.          break;
  1394.       case SM_F2O: 
  1395.          copyFileName ( inName, name );
  1396.          copyFileName ( outName, "(stdout)" ); 
  1397.          break;
  1398.    }
  1399.  
  1400.    zzz:
  1401.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  1402.       if (noisy)
  1403.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  1404.                 progName, inName );
  1405.       setExit(1);
  1406.       return;
  1407.    }
  1408.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  1409.       fprintf ( stderr, "%s: Can't open input file %s: %s.\n",
  1410.                 progName, inName, strerror(errno) );
  1411.       setExit(1);
  1412.       return;
  1413.    }
  1414.    if ( srcMode == SM_F2F && !forceOverwrite && notAStandardFile ( inName )) {
  1415.       if (noisy)
  1416.       fprintf ( stderr, "%s: Input file %s is not a normal file.\n",
  1417.                 progName, inName );
  1418.       setExit(1);
  1419.       return;
  1420.    }
  1421.    if ( /* srcMode == SM_F2F implied && */ cantGuess ) {
  1422.       if (noisy)
  1423.       fprintf ( stderr, 
  1424.                 "%s: Can't guess original name for %s -- using %s\n",
  1425.                 progName, inName, outName );
  1426.       /* just a warning, no return */
  1427.    }   
  1428.    if ( srcMode == SM_F2F && !forceOverwrite && fileExists ( outName ) ) {
  1429.       fprintf ( stderr, "%s: Output file %s already exists.\n",
  1430.                 progName, outName );
  1431.       setExit(1);
  1432.       return;
  1433.    }
  1434.    if ( srcMode == SM_F2F && !forceOverwrite &&
  1435.         (n=countHardLinks ( inName ) ) > 0) {
  1436.       fprintf ( stderr, "%s: Input file %s has %d other link%s.\n",
  1437.                 progName, inName, n, n > 1 ? "s" : "" );
  1438.       setExit(1);
  1439.       return;
  1440.    }
  1441.  
  1442.    switch ( srcMode ) {
  1443.  
  1444.       case SM_I2O:
  1445.          inStr = stdin;
  1446.          outStr = stdout;
  1447.          if ( isatty ( fileno ( stdin ) ) ) {
  1448.             fprintf ( stderr,
  1449.                       "%s: I won't read compressed data from a terminal.\n",
  1450.                       progName );
  1451.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  1452.                               progName, progName );
  1453.             setExit(1);
  1454.             return;
  1455.          };
  1456.          break;
  1457.  
  1458.       case SM_F2O:
  1459.          inStr = fopen ( inName, "rb" );
  1460.          outStr = stdout;
  1461.          if ( inStr == NULL ) {
  1462.             fprintf ( stderr, "%s: Can't open input file %s:%s.\n",
  1463.                       progName, inName, strerror(errno) );
  1464.             if ( inStr != NULL ) fclose ( inStr );
  1465.             setExit(1);
  1466.             return;
  1467.          };
  1468.          break;
  1469.  
  1470.       case SM_F2F:
  1471.          inStr = fopen ( inName, "rb" );
  1472.          outStr = fopen ( outName, "wb" );
  1473.          if ( outStr == NULL) {
  1474.             fprintf ( stderr, "%s: Can't create output file %s: %s.\n",
  1475.                       progName, outName, strerror(errno) );
  1476.             if ( inStr != NULL ) fclose ( inStr );
  1477.             setExit(1);
  1478.             return;
  1479.          }
  1480.          if ( inStr == NULL ) {
  1481.             fprintf ( stderr, "%s: Can't open input file %s: %s.\n",
  1482.                       progName, inName, strerror(errno) );
  1483.             if ( outStr != NULL ) fclose ( outStr );
  1484.             setExit(1);
  1485.             return;
  1486.          };
  1487.          setInterimPermissions ( outName );
  1488.          break;
  1489.  
  1490.       default:
  1491.          panic ( "uncompress: bad srcMode" );
  1492.          break;
  1493.    }
  1494.  
  1495.    if (verbosity >= 1) {
  1496.       fprintf ( stderr, "  %s: ", inName );
  1497.       pad ( inName );
  1498.       fflush ( stderr );
  1499.    }
  1500.  
  1501.    /*--- Now the input and output handles are sane.  Do the Biz. ---*/
  1502.    outputHandleJustInCase = outStr;
  1503.    deleteOutputOnInterrupt = True;
  1504.    magicNumberOK = uncompressStream ( inStr, outStr );
  1505.    outputHandleJustInCase = NULL;
  1506.  
  1507.    /*--- If there was an I/O error, we won't get here. ---*/
  1508.    if ( magicNumberOK ) {
  1509.       if ( srcMode == SM_F2F ) {
  1510.          copyDatePermissionsAndOwner ( inName, outName );
  1511.          deleteOutputOnInterrupt = False;
  1512.          if ( !keepInputFiles ) {
  1513.             IntNative retVal = remove ( inName );
  1514.             ERROR_IF_NOT_ZERO ( retVal );
  1515.          }
  1516.       }
  1517.    } else {
  1518.       unzFailsExist = True;
  1519.       deleteOutputOnInterrupt = False;
  1520.       if ( srcMode == SM_F2F ) {
  1521.          IntNative retVal = remove ( outName );
  1522.          ERROR_IF_NOT_ZERO ( retVal );
  1523.       }
  1524.    }
  1525.    deleteOutputOnInterrupt = False;
  1526.  
  1527.    if ( magicNumberOK ) {
  1528.       if (verbosity >= 1)
  1529.          fprintf ( stderr, "done\n" );
  1530.    } else {
  1531.       setExit(2);
  1532.       if (verbosity >= 1)
  1533.          fprintf ( stderr, "not a bzip2 file.\n" ); else
  1534.          fprintf ( stderr,
  1535.                    "%s: %s is not a bzip2 file.\n",
  1536.                    progName, inName );
  1537.    }
  1538.  
  1539. }
  1540.  
  1541.  
  1542. /*---------------------------------------------*/
  1543. static 
  1544. void testf ( Char *name )
  1545. {
  1546.    FILE *inStr;
  1547.    Bool allOK;
  1548.  
  1549.    deleteOutputOnInterrupt = False;
  1550.  
  1551.    if (name == NULL && srcMode != SM_I2O)
  1552.       panic ( "testf: bad modes\n" );
  1553.  
  1554.    copyFileName ( outName, "(none)" );
  1555.    switch (srcMode) {
  1556.       case SM_I2O: copyFileName ( inName, "(stdin)" ); break;
  1557.       case SM_F2F: copyFileName ( inName, name ); break;
  1558.       case SM_F2O: copyFileName ( inName, name ); break;
  1559.    }
  1560.  
  1561.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  1562.       if (noisy)
  1563.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  1564.                 progName, inName );
  1565.       setExit(1);
  1566.       return;
  1567.    }
  1568.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  1569.       fprintf ( stderr, "%s: Can't open input %s: %s.\n",
  1570.                 progName, inName, strerror(errno) );
  1571.       setExit(1);
  1572.       return;
  1573.    }
  1574.  
  1575.    switch ( srcMode ) {
  1576.  
  1577.       case SM_I2O:
  1578.          if ( isatty ( fileno ( stdin ) ) ) {
  1579.             fprintf ( stderr,
  1580.                       "%s: I won't read compressed data from a terminal.\n",
  1581.                       progName );
  1582.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  1583.                               progName, progName );
  1584.             setExit(1);
  1585.             return;
  1586.          };
  1587.          inStr = stdin;
  1588.          break;
  1589.  
  1590.       case SM_F2O: case SM_F2F:
  1591.          inStr = fopen ( inName, "rb" );
  1592.          if ( inStr == NULL ) {
  1593.             fprintf ( stderr, "%s: Can't open input file %s:%s.\n",
  1594.                       progName, inName, strerror(errno) );
  1595.             setExit(1);
  1596.             return;
  1597.          };
  1598.          break;
  1599.  
  1600.       default:
  1601.          panic ( "testf: bad srcMode" );
  1602.          break;
  1603.    }
  1604.  
  1605.    if (verbosity >= 1) {
  1606.       fprintf ( stderr, "  %s: ", inName );
  1607.       pad ( inName );
  1608.       fflush ( stderr );
  1609.    }
  1610.  
  1611.    /*--- Now the input handle is sane.  Do the Biz. ---*/
  1612.    allOK = testStream ( inStr );
  1613.  
  1614.    if (allOK && verbosity >= 1) fprintf ( stderr, "ok\n" );
  1615.    if (!allOK) testFailsExist = True;
  1616. }
  1617.  
  1618.  
  1619. /*---------------------------------------------*/
  1620. static 
  1621. void license ( void )
  1622. {
  1623.    fprintf ( stderr,
  1624.  
  1625.     "bzip2, a block-sorting file compressor.  "
  1626.     "Version %s.\n"
  1627.     "   \n"
  1628.     "   Copyright (C) 1996-2000 by Julian Seward.\n"
  1629.     "   \n"
  1630.     "   This program is free software; you can redistribute it and/or modify\n"
  1631.     "   it under the terms set out in the LICENSE file, which is included\n"
  1632.     "   in the bzip2-1.0 source distribution.\n"
  1633.     "   \n"
  1634.     "   This program is distributed in the hope that it will be useful,\n"
  1635.     "   but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1636.     "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
  1637.     "   LICENSE file for more details.\n"
  1638.     "   \n",
  1639.     BZ2_bzlibVersion()
  1640.    );
  1641. }
  1642.  
  1643.  
  1644. /*---------------------------------------------*/
  1645. static 
  1646. void usage ( Char *fullProgName )
  1647. {
  1648.    fprintf (
  1649.       stderr,
  1650.       "bzip2, a block-sorting file compressor.  "
  1651.       "Version %s.\n"
  1652.       "\n   usage: %s [flags and input files in any order]\n"
  1653.       "\n"
  1654.       "   -h --help           print this message\n"
  1655.       "   -d --decompress     force decompression\n"
  1656.       "   -z --compress       force compression\n"
  1657.       "   -k --keep           keep (don't delete) input files\n"
  1658.       "   -f --force          overwrite existing output files\n"
  1659.       "   -t --test           test compressed file integrity\n"
  1660.       "   -c --stdout         output to standard out\n"
  1661.       "   -q --quiet          suppress noncritical error messages\n"
  1662.       "   -v --verbose        be verbose (a 2nd -v gives more)\n"
  1663.       "   -L --license        display software version & license\n"
  1664.       "   -V --version        display software version & license\n"
  1665.       "   -s --small          use less memory (at most 2500k)\n"
  1666.       "   -1 .. -9            set block size to 100k .. 900k\n"
  1667.       "\n"
  1668.       "   If invoked as `bzip2', default action is to compress.\n"
  1669.       "              as `bunzip2',  default action is to decompress.\n"
  1670.       "              as `bzcat', default action is to decompress to stdout.\n"
  1671.       "\n"
  1672.       "   If no file names are given, bzip2 compresses or decompresses\n"
  1673.       "   from standard input to standard output.  You can combine\n"
  1674.       "   short flags, so `-v -4' means the same as -v4 or -4v, &c.\n"
  1675. #if BZ_UNIX
  1676.       "\n"
  1677. #endif
  1678.       ,
  1679.  
  1680.       BZ2_bzlibVersion(),
  1681.       fullProgName
  1682.    );
  1683. }
  1684.  
  1685.  
  1686. /*---------------------------------------------*/
  1687. static 
  1688. void redundant ( Char* flag )
  1689. {
  1690.    fprintf ( 
  1691.       stderr, 
  1692.       "%s: %s is redundant in versions 0.9.5 and above\n",
  1693.       progName, flag );
  1694. }
  1695.  
  1696.  
  1697. /*---------------------------------------------*/
  1698. /*--
  1699.   All the garbage from here to main() is purely to
  1700.   implement a linked list of command-line arguments,
  1701.   into which main() copies argv[1 .. argc-1].
  1702.  
  1703.   The purpose of this exercise is to facilitate 
  1704.   the expansion of wildcard characters * and ? in 
  1705.   filenames for OSs which don't know how to do it
  1706.   themselves, like MSDOS, Windows 95 and NT.
  1707.  
  1708.   The actual Dirty Work is done by the platform-
  1709.   specific macro APPEND_FILESPEC.
  1710. --*/
  1711.  
  1712. typedef
  1713.    struct zzzz {
  1714.       Char        *name;
  1715.       struct zzzz *link;
  1716.    }
  1717.    Cell;
  1718.  
  1719.  
  1720. /*---------------------------------------------*/
  1721. static 
  1722. void *myMalloc ( Int32 n )
  1723. {
  1724.    void* p;
  1725.  
  1726.    p = malloc ( (size_t)n );
  1727.    if (p == NULL) outOfMemory ();
  1728.    return p;
  1729. }
  1730.  
  1731.  
  1732. /*---------------------------------------------*/
  1733. static 
  1734. Cell *mkCell ( void )
  1735. {
  1736.    Cell *c;
  1737.  
  1738.    c = (Cell*) myMalloc ( sizeof ( Cell ) );
  1739.    c->name = NULL;
  1740.    c->link = NULL;
  1741.    return c;
  1742. }
  1743.  
  1744.  
  1745. /*---------------------------------------------*/
  1746. static 
  1747. Cell *snocString ( Cell *root, Char *name )
  1748. {
  1749.    if (root == NULL) {
  1750.       Cell *tmp = mkCell();
  1751.       tmp->name = (Char*) myMalloc ( 5 + strlen(name) );
  1752.       strcpy ( tmp->name, name );
  1753.       return tmp;
  1754.    } else {
  1755.       Cell *tmp = root;
  1756.       while (tmp->link != NULL) tmp = tmp->link;
  1757.       tmp->link = snocString ( tmp->link, name );
  1758.       return root;
  1759.    }
  1760. }
  1761.  
  1762.  
  1763. /*---------------------------------------------*/
  1764. static 
  1765. void addFlagsFromEnvVar ( Cell** argList, Char* varName ) 
  1766. {
  1767.    Int32 i, j, k;
  1768.    Char *envbase, *p;
  1769.  
  1770.    envbase = getenv(varName);
  1771.    if (envbase != NULL) {
  1772.       p = envbase;
  1773.       i = 0;
  1774.       while (True) {
  1775.          if (p[i] == 0) break;
  1776.          p += i;
  1777.          i = 0;
  1778.          while (isspace((Int32)(p[0]))) p++;
  1779.          while (p[i] != 0 && !isspace((Int32)(p[i]))) i++;
  1780.          if (i > 0) {
  1781.             k = i; if (k > FILE_NAME_LEN-10) k = FILE_NAME_LEN-10;
  1782.             for (j = 0; j < k; j++) tmpName[j] = p[j];
  1783.             tmpName[k] = 0;
  1784.             APPEND_FLAG(*argList, tmpName);
  1785.          }
  1786.       }
  1787.    }
  1788. }
  1789.  
  1790.  
  1791. /*---------------------------------------------*/
  1792. #define ISFLAG(s) (strcmp(aa->name, (s))==0)
  1793.  
  1794. IntNative main ( IntNative argc, Char *argv[] )
  1795. {
  1796.    Int32  i, j;
  1797.    Char   *tmp;
  1798.    Cell   *argList;
  1799.    Cell   *aa;
  1800.    Bool   decode;
  1801.  
  1802.    /*-- Be really really really paranoid :-) --*/
  1803.    if (sizeof(Int32) != 4 || sizeof(UInt32) != 4  ||
  1804.        sizeof(Int16) != 2 || sizeof(UInt16) != 2  ||
  1805.        sizeof(Char)  != 1 || sizeof(UChar)  != 1)
  1806.       configError();
  1807.  
  1808.    /*-- Initialise --*/
  1809.    outputHandleJustInCase  = NULL;
  1810.    smallMode               = False;
  1811.    keepInputFiles          = False;
  1812.    forceOverwrite          = False;
  1813.    noisy                   = True;
  1814.    verbosity               = 0;
  1815.    blockSize100k           = 9;
  1816.    testFailsExist          = False;
  1817.    unzFailsExist           = False;
  1818.    numFileNames            = 0;
  1819.    numFilesProcessed       = 0;
  1820.    workFactor              = 30;
  1821.    deleteOutputOnInterrupt = False;
  1822.    exitValue               = 0;
  1823.    i = j = 0; /* avoid bogus warning from egcs-1.1.X */
  1824.  
  1825.    /*-- Set up signal handlers for mem access errors --*/
  1826.    signal (SIGSEGV, mySIGSEGVorSIGBUScatcher);
  1827. #if BZ_UNIX
  1828. #ifndef __DJGPP__
  1829.    signal (SIGBUS,  mySIGSEGVorSIGBUScatcher);
  1830. #endif
  1831. #endif
  1832.  
  1833.    copyFileName ( inName,  "(none)" );
  1834.    copyFileName ( outName, "(none)" );
  1835.  
  1836.    copyFileName ( progNameReally, argv[0] );
  1837.    progName = &progNameReally[0];
  1838.    for (tmp = &progNameReally[0]; *tmp != '\0'; tmp++)
  1839.       if (*tmp == PATH_SEP) progName = tmp + 1;
  1840.  
  1841.  
  1842.    /*-- Copy flags from env var BZIP2, and 
  1843.         expand filename wildcards in arg list.
  1844.    --*/
  1845.    argList = NULL;
  1846.    addFlagsFromEnvVar ( &argList,  "BZIP2" );
  1847.    addFlagsFromEnvVar ( &argList,  "BZIP" );
  1848.    for (i = 1; i <= argc-1; i++)
  1849.       APPEND_FILESPEC(argList, argv[i]);
  1850.  
  1851.  
  1852.    /*-- Find the length of the longest filename --*/
  1853.    longestFileName = 7;
  1854.    numFileNames    = 0;
  1855.    decode          = True;
  1856.    for (aa = argList; aa != NULL; aa = aa->link) {
  1857.       if (ISFLAG("--")) { decode = False; continue; }
  1858.       if (aa->name[0] == '-' && decode) continue;
  1859.       numFileNames++;
  1860.       if (longestFileName < (Int32)strlen(aa->name) )
  1861.          longestFileName = (Int32)strlen(aa->name);
  1862.    }
  1863.  
  1864.  
  1865.    /*-- Determine source modes; flag handling may change this too. --*/
  1866.    if (numFileNames == 0)
  1867.       srcMode = SM_I2O; else srcMode = SM_F2F;
  1868.  
  1869.  
  1870.    /*-- Determine what to do (compress/uncompress/test/cat). --*/
  1871.    /*-- Note that subsequent flag handling may change this. --*/
  1872.    opMode = OM_Z;
  1873.  
  1874.    if ( (strstr ( progName, "unzip" ) != 0) ||
  1875.         (strstr ( progName, "UNZIP" ) != 0) )
  1876.       opMode = OM_UNZ;
  1877.  
  1878.    if ( (strstr ( progName, "z2cat" ) != 0) ||
  1879.         (strstr ( progName, "Z2CAT" ) != 0) ||
  1880.         (strstr ( progName, "zcat" ) != 0)  ||
  1881.         (strstr ( progName, "ZCAT" ) != 0) )  {
  1882.       opMode = OM_UNZ;
  1883.       srcMode = (numFileNames == 0) ? SM_I2O : SM_F2O;
  1884.    }
  1885.  
  1886.  
  1887.    /*-- Look at the flags. --*/
  1888.    for (aa = argList; aa != NULL; aa = aa->link) {
  1889.       if (ISFLAG("--")) break;
  1890.       if (aa->name[0] == '-' && aa->name[1] != '-') {
  1891.          for (j = 1; aa->name[j] != '\0'; j++) {
  1892.             switch (aa->name[j]) {
  1893.                case 'c': srcMode          = SM_F2O; break;
  1894.                case 'd': opMode           = OM_UNZ; break;
  1895.                case 'z': opMode           = OM_Z; break;
  1896.                case 'f': forceOverwrite   = True; break;
  1897.                case 't': opMode           = OM_TEST; break;
  1898.                case 'k': keepInputFiles   = True; break;
  1899.                case 's': smallMode        = True; break;
  1900.                case 'q': noisy            = False; break;
  1901.                case '1': blockSize100k    = 1; break;
  1902.                case '2': blockSize100k    = 2; break;
  1903.                case '3': blockSize100k    = 3; break;
  1904.                case '4': blockSize100k    = 4; break;
  1905.                case '5': blockSize100k    = 5; break;
  1906.                case '6': blockSize100k    = 6; break;
  1907.                case '7': blockSize100k    = 7; break;
  1908.                case '8': blockSize100k    = 8; break;
  1909.                case '9': blockSize100k    = 9; break;
  1910.                case 'V':
  1911.                case 'L': license();            break;
  1912.                case 'v': verbosity++; break;
  1913.                case 'h': usage ( progName );
  1914.                          exit ( 0 );
  1915.                          break;
  1916.                default:  fprintf ( stderr, "%s: Bad flag `%s'\n",
  1917.                                    progName, aa->name );
  1918.                          usage ( progName );
  1919.                          exit ( 1 );
  1920.                          break;
  1921.             }
  1922.          }
  1923.       }
  1924.    }
  1925.    
  1926.    /*-- And again ... --*/
  1927.    for (aa = argList; aa != NULL; aa = aa->link) {
  1928.       if (ISFLAG("--")) break;
  1929.       if (ISFLAG("--stdout"))            srcMode          = SM_F2O;  else
  1930.       if (ISFLAG("--decompress"))        opMode           = OM_UNZ;  else
  1931.       if (ISFLAG("--compress"))          opMode           = OM_Z;    else
  1932.       if (ISFLAG("--force"))             forceOverwrite   = True;    else
  1933.       if (ISFLAG("--test"))              opMode           = OM_TEST; else
  1934.       if (ISFLAG("--keep"))              keepInputFiles   = True;    else
  1935.       if (ISFLAG("--small"))             smallMode        = True;    else
  1936.       if (ISFLAG("--quiet"))             noisy            = False;   else
  1937.       if (ISFLAG("--version"))           license();                  else
  1938.       if (ISFLAG("--license"))           license();                  else
  1939.       if (ISFLAG("--exponential"))       workFactor = 1;             else 
  1940.       if (ISFLAG("--repetitive-best"))   redundant(aa->name);        else
  1941.       if (ISFLAG("--repetitive-fast"))   redundant(aa->name);        else
  1942.       if (ISFLAG("--verbose"))           verbosity++;                else
  1943.       if (ISFLAG("--help"))              { usage ( progName ); exit ( 0 ); }
  1944.          else
  1945.          if (strncmp ( aa->name, "--", 2) == 0) {
  1946.             fprintf ( stderr, "%s: Bad flag `%s'\n", progName, aa->name );
  1947.             usage ( progName );
  1948.             exit ( 1 );
  1949.          }
  1950.    }
  1951.  
  1952.    if (verbosity > 4) verbosity = 4;
  1953.    if (opMode == OM_Z && smallMode && blockSize100k > 2) 
  1954.       blockSize100k = 2;
  1955.  
  1956.    if (opMode == OM_TEST && srcMode == SM_F2O) {
  1957.       fprintf ( stderr, "%s: -c and -t cannot be used together.\n",
  1958.                 progName );
  1959.       exit ( 1 );
  1960.    }
  1961.  
  1962.    if (srcMode == SM_F2O && numFileNames == 0)
  1963.       srcMode = SM_I2O;
  1964.  
  1965.    if (opMode != OM_Z) blockSize100k = 0;
  1966.  
  1967.    if (srcMode == SM_F2F) {
  1968.       signal (SIGINT,  mySignalCatcher);
  1969.       signal (SIGTERM, mySignalCatcher);
  1970. #     if BZ_UNIX
  1971.       signal (SIGHUP,  mySignalCatcher);
  1972. #     endif
  1973.    }
  1974.  
  1975.    if (opMode == OM_Z) {
  1976.      if (srcMode == SM_I2O) {
  1977.         compress ( NULL );
  1978.      } else {
  1979.         decode = True;
  1980.         for (aa = argList; aa != NULL; aa = aa->link) {
  1981.            if (ISFLAG("--")) { decode = False; continue; }
  1982.            if (aa->name[0] == '-' && decode) continue;
  1983.            numFilesProcessed++;
  1984.            compress ( aa->name );
  1985.         }
  1986.      }
  1987.    } 
  1988.    else
  1989.  
  1990.    if (opMode == OM_UNZ) {
  1991.       unzFailsExist = False;
  1992.       if (srcMode == SM_I2O) {
  1993.          uncompress ( NULL );
  1994.       } else {
  1995.          decode = True;
  1996.          for (aa = argList; aa != NULL; aa = aa->link) {
  1997.             if (ISFLAG("--")) { decode = False; continue; }
  1998.             if (aa->name[0] == '-' && decode) continue;
  1999.             numFilesProcessed++;
  2000.             uncompress ( aa->name );
  2001.          }      
  2002.       }
  2003.       if (unzFailsExist) { 
  2004.          setExit(2); 
  2005.          exit(exitValue);
  2006.       }
  2007.    } 
  2008.  
  2009.    else {
  2010.       testFailsExist = False;
  2011.       if (srcMode == SM_I2O) {
  2012.          testf ( NULL );
  2013.       } else {
  2014.          decode = True;
  2015.          for (aa = argList; aa != NULL; aa = aa->link) {
  2016.         if (ISFLAG("--")) { decode = False; continue; }
  2017.             if (aa->name[0] == '-' && decode) continue;
  2018.             numFilesProcessed++;
  2019.             testf ( aa->name );
  2020.      }
  2021.       }
  2022.       if (testFailsExist && noisy) {
  2023.          fprintf ( stderr,
  2024.            "\n"
  2025.            "You can use the `bzip2recover' program to attempt to recover\n"
  2026.            "data from undamaged sections of corrupted files.\n\n"
  2027.          );
  2028.          setExit(2);
  2029.          exit(exitValue);
  2030.       }
  2031.    }
  2032.  
  2033.    /* Free the argument list memory to mollify leak detectors 
  2034.       (eg) Purify, Checker.  Serves no other useful purpose.
  2035.    */
  2036.    aa = argList;
  2037.    while (aa != NULL) {
  2038.       Cell* aa2 = aa->link;
  2039.       if (aa->name != NULL) free(aa->name);
  2040.       free(aa);
  2041.       aa = aa2;
  2042.    }
  2043.  
  2044.    return exitValue;
  2045. }
  2046.  
  2047.  
  2048. /*-----------------------------------------------------------*/
  2049. /*--- end                                         bzip2.c ---*/
  2050. /*-----------------------------------------------------------*/
  2051.